from django.contrib.auth.backends import ModelBackend
import re
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from users.models import User
# from django.contrib.auth.models import User

def get_user_by_account(account):
    try:
        if re.match(r'^1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            # 如果不是手机号就用username去查询
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # # 判断账号是用用户名还是手机号
        # try:
        #     if re.match(r'^1[3-9]\d{9}', username):
        #         user = User.objects.get(mobile=username)
        #     else:
        #         # 如果不是手机号就用username去查询
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None
        # 判断用户密码是否正确
        user = get_user_by_account(username)

        # 判断用户的密码和用户是否存在
        if user and user.check_password(password):
            return user


def generate_verify_email_url(user):
    """生成用户激活邮箱url"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    data = {'user_id': user.id, 'email':user.email}
    token = serializer.dumps(data)
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token.decode()
    return verify_url


def check_verify_email_token(token):
    """传入token解密后查询用户"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    try:
        data = serializer.loads(token)
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
            return user
        except User.DoesNotExist:
            return None
    except BadData:
        return None



def generate_access_token(user):
    """生成用户激活邮箱url"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    data = {'user_id': user.id}
    access_token = serializer.dumps(data).decode()
    return access_token


def check_access_token(access_token):
    """传入token解密后查询用户"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    try:
        data = serializer.loads(access_token)
        user_id = data.get('user_id')
        try:
            user = User.objects.get(id=user_id)
            return user
        except User.DoesNotExist:
            return None
    except BadData:
        return None
